<template>
  <div class="app-container">
    <el-row>
      <el-col :xs="24" class="table_big_bg">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                <el-form-item label="用户编号" prop="UserID" width="250">
                  <el-input
                    v-model="queryParams.UserID"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="用户名称" prop="UserName">
                  <el-input
                    v-model="queryParams.UserName"
                    placeholder="请输入用户名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                </el-form-item>
                </div>
              </el-form>
            </el-col>
            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
                <span>
                  {{ fold ? '收起筛选' : '更多筛选' }}
                </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
            </el-col>
          </el-row>
        <el-row :gutter="10" class="mb8" style=" padding: 10px 0px;">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:usersdb:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:usersdb:remove']"
            >批量删除</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport" :hasPermiExport="['basedata:usersdb:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="usersdbList" @selection-change="handleSelectionChange"  max-height="600px"  ref="tableList">
          <el-table-column type="selection" width="55" align="center" />
<!--          <el-table-column label="自增主键" align="center" prop="ID" />-->
<!--          <el-table-column label="用户归属水司" align="center" prop="tenantId" />-->
<!--          <el-table-column label="用户归属水司" align="center" width="55" prop="belongDepartment" />-->
          <el-table-column label="用户编号" align="center" prop="UserID" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户名称" align="center" prop="UserName" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="联系人" align="center" prop="Contacts" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="联系方式" align="center" prop="ContactsPhone" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="电子邮箱" align="center" prop="Email" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户地址" align="center" prop="UserAddress" v-if="columns[5].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="ReMark" v-if="columns[6].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="用户状态" align="center" prop="UserMark" v-if="columns[7].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.user_status" :value="scope.row.UserMark"/>
            </template>
          </el-table-column>
          <el-table-column label="立户时间" align="center" prop="createTime" width="180" v-if="columns[8].visible" :show-overflow-tooltip="true">
            <template slot-scope="scope">
             <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:usersdb:edit']"
              >修改</el-button>

              <el-button
                v-if="scope.row.UserMark === 1"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="closingAccount(scope.row)"
                v-hasPermi="['basedata:usersdb:edit']"
              >销户</el-button>

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:usersdb:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改大用户档案对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <!-- <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司"  filterable style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belongDepartment"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="用户编号" prop="UserID">
          <el-input v-model="form.UserID" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="用户名称" prop="UserName">
          <el-input v-model="form.UserName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="证件号码" prop="UserCode">
          <el-input v-model="form.UserCode" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="联系人" prop="Contacts">
          <el-input v-model="form.Contacts" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="ContactsPhone">
          <el-input v-model="form.ContactsPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="Email">
          <el-input v-model="form.Email" placeholder="请输入电子邮箱" />
        </el-form-item>
        <el-form-item label="用户地址" prop="UserAddress">
          <el-input v-model="form.UserAddress" placeholder="请输入用户地址" />
        </el-form-item>
        <el-form-item label="备注" prop="ReMark">
          <el-input v-model="form.ReMark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="删除标志" prop="DeleteMark">-->
<!--          <el-select v-model="form.DeleteMark" placeholder="请选择删除标志">-->
<!--            <el-option-->
<!--              v-for="dict in dict.type.sys_yes_no"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUsersdb, getUsersdb, delUsersdb, addUsersdb, updateUsersdb,closingAccount } from "@/api/record/usersdb";
import { getToken } from "@/utils/auth";
export default {
  name: "Usersdb",
  dicts: ['warnparamtype', 'warntargettype', 'sys_yes_no','belongDepartment','user_status'],
  data() {
    return {
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/usersdb/importData"
      },
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '120px',
      columns: [
        // { key: 0, label: `自增主键`, visible: false },
        // { key: 1, label: `设备归属水司`, visible: false },
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `联系人`, visible: true },
        { key: 3, label: `联系方式`, visible: true },
        { key: 4, label: `电子邮箱`, visible: true },
        { key: 5, label: `用户地址`, visible: true },
        { key: 6, label: `备注`, visible: true },
        { key: 7, label: `用户状态`, visible: true },
        { key: 8, label: `立户时间`, visible: true },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 大用户档案表格数据
      usersdbList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        UserID: null,
        UserName: null,
        UserType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "用户归属水司不能为空", trigger: "blur" }
        // ],
        UserID: [
          { required: true, message: "用户编号不能为空", trigger: "blur" }
        ],
        UserName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        IdType: [
          { required: true, message: "证件类型不能为空", trigger: "change" }
        ],
        ContactsPhone: [
          { required: true, message: "联系方式不能为空", trigger: "blur" }
        ],
        Email: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    initTable(){
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.tableList.doLayout()
        }, 100)
      })
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    handleImport() {
      this.upload.title = "大用户表用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 查询大用户档案列表 */
    getList() {
      this.loading = true;
      listUsersdb(this.queryParams).then(response => {
        this.usersdbList = response.rows;
        this.total = response.total;
        this.initTable()
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: '710170',
        UserID: null,
        UserName: null,
        UserType: null,
        IdType: null,
        UserCode: null,
        Contacts: null,
        ContactsPhone: null,
        Email: null,
        UserAddress: null,
        ReMark: null,
        DeleteMark: null,
        UserMark: null,
        createTime: null
      };
      this.resetForm("form");
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      this.selectOptions.label = data.label
      this.selectOptions.value = data.id
      this.form.areaCode = data.id
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加大用户档案";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getUsersdb(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改大用户档案";
      });
    },
    /** 销户按钮操作 */
    closingAccount(row) {
      let that = this;
      this.reset();
      const ID = row.ID
      this.$modal.confirm('是否确认销户操作？').then(function() {
        closingAccount(parseInt(ID)).then(response => {
          debugger
          if(response.code== 200){
            that.$modal.msgSuccess("销户成功");
          }else{
            that.$modal.msgError("销户异常");
          }
        });
      }).then(() => {
        this.getList();
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ID != null) {
            updateUsersdb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUsersdb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.ID || this.ids;
      // this.$modal.confirm('是否确认删除大用户档案编号为"' + IDs + '"的数据项？').then(function() {
      this.$modal.confirm('是否确认删除用户档案？').then(function() {
        return delUsersdb(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/usersdb/export', {
        ...this.queryParams
      }, `usersdb_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
  .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
</style>
